/*
 * lotura - GWT databinding
 * Copyright (C) 2008  Juanjo García Latre
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package net.inttes.lotura.binding.adapter;

import java.util.Iterator;
import java.util.List;

import net.inttes.lotura.binding.Binding;
import net.inttes.lotura.binding.value.ValueModel;
import net.inttes.lotura.list.ListModel;
import net.inttes.lotura.list.ListModelListener;

import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;


public class ListBoxBinding implements Binding {

	private ListBox listBox; 
	private ValueModel selectionHolder;
	private SelectionInList selectionInList;
	private Binding indexBinding;
	private ListModelListener listChangeHandler = new ListChangeHandler();
	
	
	public ListBoxBinding(ListBox listBox, ValueModel selectionHolder, ListModel listModel) {
		this.listBox = listBox;
		this.selectionHolder = selectionHolder;
		listModel.addListener( listChangeHandler );
	}
	
	
	public Widget getWidget() {
		return listBox;
	}
	

	public void unbind() {
		selectionInList.release();
		indexBinding.unbind();
	}

	//---------------------------------------------------------------

	private class ListChangeHandler implements ListModelListener {
		public void onDataChanged(ListModel model) {
			//TODO hacer unbind si la lista cambia más de una vez
			loadListBox( model.getItems() );
			selectionInList = new SelectionInList( model.getKeys(), selectionHolder );
			indexBinding = new ListBoxIndexAdapter(listBox, selectionInList.getSelectionIndexHolder());
		}					
	}
	
	
	private void loadListBox(List items) {
		listBox.clear();
		for (Iterator it = items.iterator(); it.hasNext();) {
			listBox.addItem( String.valueOf(it.next()) );			
		}
	}
	
}
